'use strict';

var mongoose = require('mongoose'),
  validator = require('mongoose-validator');
var modelPlugin = require("../model.plugin");
var Schema = mongoose.Schema;
var ObjectId  = Schema.ObjectId;

var userSchema = new Schema({
  userName: {type: String, required: true, unique: true, minlength: 6, maxlength: 20/*, validate: nameValidator*/},
  niceName: {type: String/*, validate: nameValidator*/},
  passWord: {type: String, required: true},
  phone: {type: String},
  email: {type: String},
  firstName: {type: String/*, validate: nameValidator*/},
  lastName: {type: String/*, validate: nameValidator*/},
  middleName: {type: String/*, validate: nameValidator*/},
  idCard: {type: String},
  avatar: {type: String},
  url: {type: String},
  location: {type: String},
  profile: {type: String },
  imageUrl: {type: String},

  age: {type: Number, min: 1, max: 120},
  //{0: none, 1: man, 2: woman}
  gender: {type: Number, enum:[0, 1, 2], default: 0},
  //{0: disable, 1: used, 2: ...}
  state: {type: Number, enum:[0, 1, 2], default: 1},
  birthday: {type: Date},
  //{0: none, 1: all can see, 2: friend, 3: choose list}
  publicity: {type: Number, enum:[0, 1, 2, 3], default: 0},

  //wechat
  openId: {type: String},
  city: {type: String},
  country: {type: String},
  province: {type: String},
  language: {type: String},
  headimgUrl: {type: String},
  subscribeTime: {type: Date},
  unionId: {type: String},
  remark: {type: String},
  groupId: {type: String},
  wechatToken: {type: String},

  createdAt: {type: Date, default: Date.now},
  createdBy: {type: ObjectId, ref: 'User'},
  updatedAt: {type: Date, default: Date.now},
  updatedBy: {type: ObjectId, ref: 'User'},
  accessToken: {type: String},

  roleId: {type: ObjectId, ref: 'Role'},
  /*relationship: [{
    name: {type: String},
    userIdList: [{type: ObjectId, ref: 'User'}]
  }],*/
  tags: [{
    name: {type: String}
  }]
});

userSchema.plugin(modelPlugin);
userSchema.index({userName: 1});

/*userSchema.statics.checkUserName = function(obj) {
  var promise = this.findOne({userName: obj.userName}, function(err, user) {
    console.log('checkUserName:', err, user._id);
    if (err == null) {
      if (user == null) {
        return true;
      } else {
        return false;
      }
    } else {
      throw new Error('checkUserName err:', err);
    }
  }).exec();
  promise.then(function(user) {
    console.log('checkUserName:', user);
    if (user == null) {
      return true;
    } else {
      return false;
    }
  }).
  catch(function(err) {
    console.log('checkUserName err:', err);
    throw new Error('checkUserName err:', err);
  });
}*/

var nameValidator = [
  validator({
    validator: 'isAlphanumeric',
    passIfEmpty: true,
    message: 'Name should contain alpha-numeric characters only'
  })
];

mongoose.model('User', userSchema);
